package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求uri
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        // 判断是不是登录请求，是就放行
        if (uri.endsWith("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取token
        String token = request.getHeader("Token");
        if (!StringUtils.hasLength(token)) {
            response.setStatus(401);
            return;
        }

        // 解析token
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("解析令牌出错了", e);
            response.setStatus(401);
            return;
        }

        // 放行
        filterChain.doFilter(request, response);
    }
}
